package com.yjyw.tiexie.activity.mine;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ToastUtils;
import com.yjyw.tiexie.R;
import com.yjyw.tiexie.bean.AttachmentListBean;
import com.yjyw.tiexie.common.BaseActivity;
import com.yjyw.tiexie.common.net.NetCallBack;
import com.yjyw.tiexie.common.permission.PermissionManager;
import com.yjyw.tiexie.js.BridgeWebView;
import com.yjyw.tiexie.util.FileUtils;
import com.yjyw.tiexie.util.GsonUtil;
import com.yjyw.tiexie.util.LogUtil;
import com.yjyw.tiexie.util.PictureSelectorGlideEngine;
import com.yjyw.tiexie.util.StringUtil;
import com.yjyw.tiexie.util.TimeUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebActivity extends BaseActivity implements NetCallBack {
    @BindView(R.id.web_view)
    BridgeWebView webView;

    String url = "";
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.iv_left_close)
    ImageView ivLeftClose;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;


    private String AccessKeyId, SecretKeyId, SecurityToken;
    String dirname = "h5Image/";
    String bucketName = "";
    private String endpoint;
    List<LocalMedia> selectList = new ArrayList<>();

    private CallBackFunction callBackFunction;

    @Override
    protected int getContentView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            WebView.enableSlowWholeDocumentDraw();
        }
        return R.layout.activity_web;
    }


    @Override
    protected void init() {
        url = getIntent().getStringExtra("url");
        LogUtil.e("url:", url);
        webView.clearCache(true);
        webView.setDefaultHandler(new DefaultHandler());
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        webView.setScrollContainer(false);
        webView.getSettings().setJavaScriptEnabled(true);// 设置webview_xieyi控件可以加载JavaScript代码
        webView.getSettings().setBuiltInZoomControls(true);
        //不显示webview缩放按钮
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setDomStorageEnabled(true);
        webView.loadUrl(url);
        registerHandler();
    }


    private void registerHandler() {

        webView.registerHandler("CALL_CAMERA", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.e("getUserData", "handler = getUserData, data from web = " + data);
                //data是js给的参数，参数可用可不用，然后回调给js数据
//                function.onCallBack(new Gson().toJson(jsUserInfo));
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView webView, String s) {
                getWebTitle();
                super.onReceivedTitle(webView, s);
            }

//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//                LogUtil.e("newProgress", newProgress + "");
//                //显示进度条
//                progressBar.setProgress(newProgress);
//                if (newProgress == 100) {
//                    //加载完毕隐藏进度条
//                    progressBar.setVisibility(View.GONE);
//                }
//                super.onProgressChanged(view, newProgress);
//            }
        });


    }


    TimePickerView pvTime;
    private boolean isDownlading;

    private void downloadImg(String imgUrl) {
        if (!isDownlading) {
            //如果不是正在下载，则开始下载
            isDownlading = true;
            new DownloadImgTask(0).execute(imgUrl);
        }
    }

    @SuppressLint("StaticFieldLeak")
    class DownloadImgTask extends AsyncTask<String, Integer, Void> {

        private int mPosition;

        public DownloadImgTask(int position) {
            mPosition = position;
        }

        @Override
        protected Void doInBackground(String... params) {
            String imgUrl = params[0];
            File file = null;
            try {
                FutureTarget<File> future = Glide
                        .with(WebActivity.this)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                file = future.get();

                String filePath = file.getAbsolutePath();
                String destFileName = System.currentTimeMillis() + FileUtils.getImageFileExt(filePath);
                File destFile = new File(FileUtils.getDir(""), destFileName);

                FileUtils.copy(file, destFile);// 保存图片

                // 最后通知图库更新
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(new File(destFile.getPath()))));
            } catch (Exception e) {
                LogUtil.e("WebActivity", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            isDownlading = false;
            ToastUtils.s(WebActivity.this, "保存成功");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
//         KLog.i(TAG,"progress: " + values[0]);
        }
    }

    private static final int PHONE_REQUEST_CODE = 1000;

    public void postFunction(CallBackFunction function) {
        if (listBeans != null) {
            String json = GsonUtil.getJson(listBeans);
            function.onCallBack(json);
            listBeans = null;
        }
    }


    // Create an image file
    private File createImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName, ".jpg", storageDir);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack()) {
            onWebViewGoBack();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void getWebTitle() {
        WebBackForwardList forwardList = webView.copyBackForwardList();
        WebHistoryItem item = forwardList.getCurrentItem();
        if (item != null) {
            tvTitle.setText(item.getTitle());
        }
    }

    private void onWebViewGoBack() {
//        webView.clearHistory();
//        webView.clearFormData();
//        webView.clearCache(true);
        webView.goBack();
        getWebTitle();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }
            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();
            webView.destroy();
        }
        super.onDestroy();
    }

    @OnClick({R.id.iv_left, R.id.iv_left_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left:
                //返回上级
                if (webView.canGoBack()) {
                    selectList.clear();
                    onWebViewGoBack();
                } else {
                    finish();
                }
                break;
            case R.id.iv_left_close:
//                finish();
                webView.callHandler("test", "123", new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {

                    }
                });
                break;
        }
    }

    @Override
    public void onResponse(boolean flag, int requestCode, String result) throws Exception {
        switch (requestCode) {
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //初始化oss

                    break;
                case 2:
                    LogUtil.e("-saveFinish-", "-----------saveFinish--------");
                    webView.callHandler("saveFinish", json, new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {

                        }
                    });
                    break;
                case 3:
                    webView.callHandler("androidPic", json, new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {
                        }
                    });
                    break;
            }
        }
    };


    int themeId = R.style.picture_default_style;
    private int chooseMode = PictureMimeType.ofImage();

    private void pickMedia() {

        PictureSelector.create(WebActivity.this)
                .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .loadImageEngine(PictureSelectorGlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                .isWeChatStyle(false)// 是否开启微信图片选择风格
                .isWithVideoImage(false)// 图片和视频是否可以同选,只在ofAll模式下有效
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .maxVideoSelectNum(1) // 视频最大选择数量，如果没有单独设置的需求则可以不设置，同用maxSelectNum字段
//                    .minVideoSelectNum(1)// 视频最小选择数量，如果没有单独设置的需求则可以不设置，同用minSelectNum字段
                .imageSpanCount(3)// 每行显示个数
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                //.isAndroidQTransform(false)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && enableCrop(false);有效,默认处理
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                .previewImage(true)// 是否可预览图片
                .previewVideo(true)// 是否可预览视频
                .enablePreviewAudio(true) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .compress(true)// 是否压缩
                .compressQuality(80)// 图片压缩后输出质量 0~ 100
                .synOrAsy(true)//同步false或异步true 压缩 默认同步
                .compressFocusAlpha(false)//不要alpha channel
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(true)// 是否显示gif图片
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                //.isDragFrame(false)// 是否可拖动裁剪框(固定)
                .videoMaxSecond(300)
                .cutOutQuality(90)// 裁剪输出质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .recordVideoSecond(15)//录制视频秒数 默认60s
                .setMaxZoneImageSize(5)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia localMedia : selectList) {
                        if (!StringUtil.isEmpty(localMedia.getCompressPath())
                                && ("/".equals(localMedia.getCompressPath()) || localMedia.getCompressPath().length() == 1)) {
                            localMedia.setCompressPath(FileUtils.getRealPath(this, localMedia.getPath()));
                        } else {
                            localMedia.setCompressPath(FileUtils.getRealPath(this, localMedia.getPath()));
                        }
                    }
                    //上傳圖片

                }
                break;
        }
    }


    private boolean flag;
    private AttachmentListBean listBeans;


    private String json = "";

    private void doAction(Activity activity) {
        PermissionManager.inflate(activity, PHONE_REQUEST_CODE);
        json = GsonUtil.getJson(listBeans);
//        callBackFunction.onCallBack(json);

        Message message = new Message();
        message.what = 3;
        handler.sendMessage(message);


        hideProgressNoMiss();

    }


    @Override
    public void tokenTimeOut(int requestCode) {

    }

    class test {
        private String ms;
    }
}
